package com.itheima.health.service.impl;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.security.SecureRandom;

@DubboService
@Slf4j
public class SmsServiceImpl implements SmsService {
    private JedisPool jedisPool = new JedisPool();
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * @Author: 位帅帅
     * @Date: 20:05 2021/1/11
     * @Params: [type, telephone]
     * @RerurnType: java.lang.Integer
     * @Description: 生成验证码
     */
    @Override
    public Integer sendValidateCode(String type, String telephone) {
        log.info("[生成验证码-参数]type: {}, telephone: {}", type, telephone);
        Integer code = (int) (1000 + new SecureRandom().nextDouble() * 8999);
        String redisKey = RedisConst.VALIDATA_CODE_PREFILX + type + ": " + telephone;
//        if (!StringUtils.isEmpty(redisTemplate.opsForValue().get(redisKey))) {
//            redisTemplate.delete(redisKey);
//        }
//        System.out.println(redisTemplate.opsForValue().get(redisKey));
//        redisTemplate.opsForValue().set(redisKey,code,);
        try (Jedis jedis = jedisPool.getResource()) {
            if (!StringUtils.isEmpty(jedis.get(redisKey))) {
                jedis.del(redisKey);
            }
            jedis.setex(redisKey,5*60,String.valueOf(code));
        }
        return code;
    }

    /**
     * @Author: 位帅帅
     * @Date: 20:29 2021/1/11
     * @Params: []
     * @RerurnType: boolean
     * @Description: 验证验证码
     */
    @Override
    public boolean checkValidateCode(String validateCodeType, String telephone, String validateCode) {
        log.info("[验证验证码-参数]validateCodeType: {}, telephone: {}, validateCode: {}", validateCodeType, telephone, validateCode);
        String redisKey = RedisConst.VALIDATA_CODE_PREFILX + validateCodeType + ": " + telephone;
        try (Jedis jedis = jedisPool.getResource()) {
            String value = jedis.get(redisKey);
            if (!StringUtils.isEmpty(value) && value.equals(validateCode)) {
                jedis.del(redisKey);
                return true;
            } else {
                return false;
            }
        }
        /*if (!StringUtils.isEmpty(redisValue) && redisValue.equals(validateCode)) {
            redisTemplate.delete(redisKey);
            return true;
        } else {
            return false;
        }*/
    }
}
